package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.JSONObjectPro;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.comlbs.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.request.equipment.BatchUpdateParam;
import com.ruoyi.system.domain.vo.bigscreen.DeviceDriver;
import com.ruoyi.system.domain.vo.common.DeviceGps;
import com.ruoyi.system.domain.vo.equipment.EquipmentInfo;
import com.ruoyi.system.domain.vo.equipment.NumberPlateDeviceId;
import com.ruoyi.system.domain.vo.common.ComDvoName;
import com.ruoyi.system.mapper.EquipmentManagementMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.ComLbsUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 设备管理Service业务层处理
 *
 * @author wp
 * @date 2023-08-10
 */
@Service
public class EquipmentManagementServiceImpl extends ServiceImpl<EquipmentManagementMapper, EquipmentManagement> implements IEquipmentManagementService {

    @Autowired
    private EquipmentManagementMapper equipmentManagementMapper;
    @Autowired
    private CommonService commonService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IVehicleEquipmentService vehicleEquipmentService;
    @Autowired
    private IDriverEquipmentService driverEquipmentService;
    @Autowired
    private IVehicleManagementService vehicleManagementService;
    @Autowired
    private IDriverInfoService driverInfoService;
    @Autowired
    private ISimCardService simCardService;
    @Autowired
    private IAlarmRulePersonVehicleService alarmRulePersonVehicleService;
    @Autowired
    private IUploadPlatformRecordService uploadPlatformRecordService;

    /**
     * 查询设备管理列表
     *
     * @param param 设备管理
     * @return 设备管理
     */
    @DataScope
    @Override
    public List<EquipmentInfo> selectList(EquipmentInfo param) {
        return equipmentManagementMapper.list(param);
    }

    @DataScope
    @Override
    public List<EquipmentInfo> selectListBaseInfo(EquipmentInfo param) {
        return equipmentManagementMapper.listBaseInfo(param);
    }

    @Override
    public EquipmentInfo selectOne(Long id) {
        return equipmentManagementMapper.get(id);
    }

    /**
     * 新增设备管理
     *
     * @param param 设备管理
     * @return 结果
     */
    @Transactional
    @Override
    public void insertEquipment(EquipmentInfo param) {
        if (ObjectUtils.isEmpty(param.getDeviceId()) || ObjectUtils.isEmpty(param.getCompanyId())
                || ObjectUtils.isEmpty(param.getObjIcon()) || ObjectUtils.isEmpty(param.getNumberPlate())){
            throw new ServiceException("必填参数不能为空");
        }
        EquipmentManagement existOne = getByDeviceId(param.getDeviceId());
        if (existOne != null && !existOne.getId().equals(param.getEquipmentId())) throw new ServiceException("设备号已被占用");
        EquipmentManagement equipment = param.toEquipment();
        //默认为车载设备
        equipment.setEquipmentType(EquipmentTypeEnum.VEHICLE.getCode());
        //自检状态默认为未自检
        equipment.setCheckStatus(SelfCheckStatusEnum.NO_CHECK.getCode());
        //设置为已绑定
        equipment.setBindStatus(BindStatusEnum.BINDING.getCode());
        //更新激活状态
        equipment.updateActivateStatus(deptService);
        //新增设备
        equipmentManagementMapper.insert(equipment);

        //监管对象处理
        VehicleManagement object = param.toObject();
        object.setBindStatus(BindStatusEnum.BINDING.getCode());
        if (object.getId() != null){
            //处理监管对象图片
            VehicleManagement oldObject = vehicleManagementService.getById(object.getId());
            ComLbsUtils.fileHandle(oldObject.getVehiclePic(), object.getVehiclePic(), false);
            //更新监管对象信息
            vehicleManagementService.updateById(object);
        }else {
            //新增监管对象
            vehicleManagementService.save(object);
        }
        //设备与监管对象建立绑定关系
        vehicleEquipmentService.save(new VehicleEquipment(object.getId(), equipment.getId()));

        //负责人处理
        DriverInfo driver = param.toDriver();
        if (StringUtils.isNotEmpty(param.getDriverName())){
            if (param.getDriverId() != null){
                //处理负责人图片
                DriverInfo oldDriver = driverInfoService.getById(param.getDriverId());
                ComLbsUtils.fileHandle(oldDriver.getPicture(), driver.getPicture(), true);
                //更新监管对象信息
                driverInfoService.updateDriverInfo(driver);
            }else {
                //新增负责人
                driverInfoService.save(driver);
            }
            //设备与负责人建立绑定关系
            driverEquipmentService.save(new DriverEquipment(driver.getId(), equipment.getId()));
        }
    }

    /**
     * 修改设备管理
     *
     * @param newEquipment 设备管理
     * @return 结果
     */
    @Transactional
    @Override
    public void updateEquipment(EquipmentInfo newEquipment) {
        if (ObjectUtils.isEmpty(newEquipment.getEquipmentId()) || ObjectUtils.isEmpty(newEquipment.getDeviceId()) || ObjectUtils.isEmpty(newEquipment.getCompanyId())
                || ObjectUtils.isEmpty(newEquipment.getObjIcon()) || ObjectUtils.isEmpty(newEquipment.getNumberPlate())){
            throw new ServiceException("必填参数不能为空");
        }
        EquipmentInfo oldEquipment = selectOne(newEquipment.getEquipmentId());
        EquipmentManagement equipment = oldEquipment.toEquipment();

        //处理SIM卡信息，之前或现在不为空，需处理，都为空不用管
        if (StringUtils.isNotEmpty(equipment.getSimId()) || StringUtils.isNotEmpty(newEquipment.getSimId())) {
            if (StringUtils.isEmpty(equipment.getSimId()) && StringUtils.isNotEmpty(newEquipment.getSimId())) {
                //之前没有现在有，新增SIM卡
                SimCard simCard = simCardService.getSimCardInfo(newEquipment.getSimId());
                simCard.setEquipmentId(newEquipment.getEquipmentId()).setIccid(newEquipment.getSimId());
                simCardService.save(simCard);
            } else if (StringUtils.isNotEmpty(equipment.getSimId()) && StringUtils.isEmpty(newEquipment.getSimId())) {
                //之前有现在没有，删除SIM卡
                simCardService.remove(new QueryWrapper<SimCard>().eq("iccid", equipment.getSimId()));
            } else if (!equipment.getSimId().equals(newEquipment.getSimId())) {
                // 之前、现在都有，但是不一致，删除之前的，新增现在的
                SimCard simCard = simCardService.getSimCardInfo(newEquipment.getSimId());
                simCard.setEquipmentId(newEquipment.getEquipmentId()).setIccid(newEquipment.getSimId());
                simCardService.save(simCard);
                simCardService.remove(new QueryWrapper<SimCard>().eq("iccid", equipment.getSimId()));
            }
        }

        //更新设备信息
        equipment.setCompanyId(newEquipment.getCompanyId())
                .setDeviceModel(newEquipment.getDeviceModel())
                .setDeviceId(newEquipment.getDeviceId())
                .setSimId(newEquipment.getSimId())
                .setChannelsNum(newEquipment.getChannels())
                .setRemark(newEquipment.getRemark());
        //更新激活状态
        equipment.updateActivateStatus(deptService);
        //设置为已绑定
        equipment.setBindStatus(BindStatusEnum.BINDING.getCode());
        updateById(equipment);

        //处理监管对象
        VehicleManagement object = newEquipment.toObject();
        object.setBindStatus(BindStatusEnum.BINDING.getCode());
        if (oldEquipment.getVehicleId() == null){
            if (newEquipment.getVehicleId() == null) {
                //原本没有监管对象，新增监管对象
                vehicleManagementService.save(object);
            } else {
                // 此监管对象已经存在，修改信息
                VehicleManagement oldObject = vehicleManagementService.getById(newEquipment.getVehicleId());
                ComLbsUtils.fileHandle(oldObject.getVehiclePic(), object.getVehiclePic(), false);
                vehicleManagementService.updateById(object);
            }
            //设备与监管对象建立绑定关系
            vehicleEquipmentService.save(new VehicleEquipment(object.getId(), equipment.getId()));
        }else if (oldEquipment.getVehicleId().equals(newEquipment.getVehicleId())){
            //没换监管对象，更新监管对象信息即可
            VehicleManagement oldObject = vehicleManagementService.getById(oldEquipment.getVehicleId());
            ComLbsUtils.fileHandle(oldObject.getVehiclePic(), object.getVehiclePic(), false);
            vehicleManagementService.updateById(object);
        }else {
            //更换了监管对象
            //删除旧的监管对象-设备关系（解绑）
            vehicleEquipmentService.remove(new QueryWrapper<VehicleEquipment>()
                    .eq("vehicle_id", oldEquipment.getVehicleId())
                    .eq("equipment_id", oldEquipment.getEquipmentId()));
            //修改监管对象绑定状态
            vehicleManagementService.updateById(vehicleManagementService.selectOne(oldEquipment.getVehicleId()).setBindStatus(BindStatusEnum.UNBINDING.getCode()));
            //删除旧的监管对象-报警规则关系（解绑）
            alarmRulePersonVehicleService.remove(new QueryWrapper<AlarmRulePersonVehicle>().eq("business_id", oldEquipment.getVehicleId()));
            //设备绑定状态修改
            if (newEquipment.getVehicleId() == null) {
                //新增监管对象
                vehicleManagementService.save(object);
            } else {
                //更新监管对象
                VehicleManagement oldObject = vehicleManagementService.getById(oldEquipment.getVehicleId());
                ComLbsUtils.fileHandle(oldObject.getVehiclePic(), object.getVehiclePic(), false);
                vehicleManagementService.updateById(object);
            }
            //设备与监管对象建立绑定关系
            vehicleEquipmentService.save(new VehicleEquipment(object.getId(), equipment.getId()));
        }

        //处理负责人信息
        DriverInfo driver = newEquipment.toDriver();
        if (oldEquipment.getDriverId() == null){
            //原本没有负责人，绑定负责人
            if (StringUtils.isNotEmpty(newEquipment.getDriverName())){
                driverInfoService.saveOrUpdate(driver);
                driverEquipmentService.save(new DriverEquipment(driver.getId(), equipment.getId()));
            }
        }else {
            //原本有负责人
            if (!oldEquipment.getDriverId().equals(newEquipment.getDriverId())){
                //换了负责人，删除旧的负责人-设备关系（解绑）
                driverEquipmentService.remove(new QueryWrapper<DriverEquipment>()
                        .eq("driver_id", oldEquipment.getDriverId())
                        .eq("equipment_id", oldEquipment.getEquipmentId()));
                if (newEquipment.getDriverId() != null){
                    //更新负责人
                    DriverInfo oldDriver = driverInfoService.getById(oldEquipment.getDriverId());
                    ComLbsUtils.fileHandle(oldDriver.getPicture(), driver.getPicture(), true);
                    driverInfoService.updateById(driver);
                    //负责人-设备建立绑定关系
                    driverEquipmentService.save(new DriverEquipment(driver.getId(), equipment.getId()));
                }else if (StringUtils.isNotEmpty(newEquipment.getDriverName())){
                    //新增负责人
                    driverInfoService.save(driver);
                    //负责人-设备建立绑定关系
                    driverEquipmentService.save(new DriverEquipment(driver.getId(), equipment.getId()));
                }
            }else {
                //没换负责人，更新负责人信息
                DriverInfo oldDriver = driverInfoService.getById(oldEquipment.getDriverId());
                ComLbsUtils.fileHandle(oldDriver.getPicture(), driver.getPicture(), true);
                driverInfoService.updateById(driver);
            }
        }
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public void deleteEquipment(Long[] ids) {
        for (Long id : ids) {
            deleteEquipment(id);
        }
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public void deleteEquipment(Long id) {
        EquipmentInfo equipmentInfo = selectOne(id);
        if (equipmentInfo == null) throw new ServiceException("设备不存在");
        //删除监管对象
        removeById(equipmentInfo.getEquipmentId());
        if (equipmentInfo.getVehicleId() != null){
            //有监管对象，删除设备-监管对象信息（解绑）
            vehicleEquipmentService.remove(new QueryWrapper<VehicleEquipment>()
                    .eq("equipment_id", equipmentInfo.getEquipmentId())
                    .eq("vehicle_id", equipmentInfo.getVehicleId()));
            vehicleManagementService.updateById(new VehicleManagement()
                    .setId(equipmentInfo.getVehicleId())
                    .setBindStatus(BindStatusEnum.UNBINDING.getCode()));
            //删除监管对象-报警规则关系（解绑）
            alarmRulePersonVehicleService.remove(new QueryWrapper<AlarmRulePersonVehicle>().eq("business_id", equipmentInfo.getVehicleId()));
        }
        //删除负责人
        if (equipmentInfo.getDriverId() != null) {
            // 有监管对象，删除设备-负责人信息（解绑）
            driverEquipmentService.remove(new QueryWrapper<DriverEquipment>()
                    .eq("equipment_id", equipmentInfo.getEquipmentId())
                    .eq("driver_id", equipmentInfo.getDriverId()));
        }
        //SIM卡信息删除
        if (StringUtils.isNotEmpty(equipmentInfo.getSimId())) {
            simCardService.remove(new QueryWrapper<SimCard>().eq("iccid", equipmentInfo.getSimId()));
        }
        //删除设备的上传平台记录
        uploadPlatformRecordService.remove(new QueryWrapper<UploadPlatformRecord>().eq("device_id", equipmentInfo.getDeviceId()));
    }

    @Override
    public EquipmentManagement getByDeviceId(String deviceId) {
        return equipmentManagementMapper.selectOne(new QueryWrapper<EquipmentManagement>().eq("device_id", deviceId));
    }

    @Override
    public RealtimePositioning getVehiclePositionByDeviceId(String deviceId) {
        return equipmentManagementMapper.getVehiclePositionByDeviceId(deviceId);
    }

    @Override
    public List<NumberPlateDeviceId> listNumberPlateByDeviceId(String deviceId) {
        return equipmentManagementMapper.listNumberPlateByDeviceId(new JSONObjectPro().put("deviceId", deviceId));
    }

    /**
     * 设备自检
     * @param ids
     * @return
     */
    @Override
    public int equipmentCheck(List<Long> ids){
        // 自检结果
        Collector<SysDictData, ?, Map<String, SysDictData>> collector = Collectors.toMap(SysDictData::getDictValue, Function.identity());
        List<SysDictData> dictDataList = DictUtils.getDictCache("checkStatus");
        Map<String, SysDictData> dictMap = dictDataList.stream().collect(collector);
        // sts异常
        Map<String, SysDictData> stsError = dictDataList.stream().filter(i -> "sts".equals(i.getRemark())).collect(collector);
        // pop异常
        Map<String, SysDictData> popError = dictDataList.stream().filter(i -> "pop".equals(i.getRemark())).collect(collector);
        // alm异常
        Map<String, SysDictData> almError = dictDataList.stream().filter(i -> "alm".equals(i.getRemark())).collect(collector);
        // 查询设备
        List<EquipmentManagement> equipmentList = ObjectUtils.isEmpty(ids) ? list() : listByIds(ids);
        // 设备最新状态获取
        Map<String, DeviceGps> onlineData = commonService.getDeviceOnlineDataFromCache();
        // 自检不通过数量
        int notPassCount = 0;
        if (ObjectUtils.isEmpty(equipmentList)) return notPassCount;
        for (EquipmentManagement equipment : equipmentList) {
            DeviceGps device = onlineData.get(equipment.getDeviceId());
            if (device == null) {
                // 没有此设备定位信息，状态设为未连接网关，结果设为未连接网关
                equipment.setCheckStatus(SelfCheckStatusEnum.NOT_CONNECT_GATEWAY.getCode());
                equipment.setCheckDetail(SelfCheckStatusEnum.NOT_CONNECT_GATEWAY.getText());
                notPassCount++;
            } else {
                // 有此设备定位数据
                long now = System.currentTimeMillis();
                if (now - device.getGte() < VehicleStatusEnum.offlineTime) {  // 在线(5分钟内)
                    // 自检结果异常种类
                    StringBuilder result = new StringBuilder();
                    // sts异常(不包含代表有异常)
                    List<Integer> sts = device.getSts();
                    stsError.forEach((code, dict) -> {
                        if (!sts.contains(Integer.parseInt(code))) result.append(dict.getDictLabel()).append(",");
                    });
                    // pop异常
                    JSONObject popMap = device.getPop();
                    popMap.forEach((k, v) -> {
                        SysDictData dict = dictMap.get(k);
                        if (dict != null){
                            if (Integer.parseInt(k) == SelfCheckResultEnum.VIDEO_LOSS.getCode()
                                    || Integer.parseInt(k) == SelfCheckResultEnum.VIDEO_BLOCK.getCode()) {
                                // 244、245视频相关异常是list不为空才是有问题
                                String pop = v.toString();
                                if (!"".equals(pop) && !"[]".equals(pop)) {
                                    result.append(dict.getDictLabel()).append(",");
                                }
                            } else {
                                result.append(dict.getDictLabel()).append(",");
                            }
                        }
                    });
                    // alm异常
                    List<Integer> alm = device.getAlm();
                    almError.forEach((code, dict) -> {
                        if (!alm.contains(Integer.parseInt(code))) result.append(dict.getDictLabel()).append(",");
                    });
                    if (StringUtils.isEmpty(result)) {  // 没异常
                        // 状态设为通过，结果设为通过
                        equipment.setCheckStatus(SelfCheckStatusEnum.PASS.getCode());
                        equipment.setCheckDetail(SelfCheckResultEnum.PASS.getText());
                    } else { // 有异常
                        // 状态设为未通过，结果按异常拼接
                        equipment.setCheckStatus(SelfCheckStatusEnum.NOT_PASS.getCode());
                        equipment.setCheckDetail(result.substring(0, result.length() - 1));
                        notPassCount++;
                    }
                } else {  // 离线
                    // 状态设为离线，结果设为离线
                    equipment.setCheckStatus(SelfCheckStatusEnum.OFFLINE.getCode());
                    equipment.setCheckDetail(SelfCheckResultEnum.OFFLINE.getText());
                    notPassCount++; // 离线也算未通过
                }
            }
            equipment.setCheckTime(new Date()).setUpdateBy(UserConstants.ADMIN_ID);
        }
        updateBatchById(equipmentList);
        return notPassCount;
    }

    @Override
    @Transactional
    public void batchUpdateCompany(BatchUpdateParam param) {
        //激活信息修改
        if (deptService.getWaitSaleCompany().getDeptId().equals(param.getCompanyId())){
            // 如果目标公司是出厂待销售，修改设备激活状态为未激活
            equipmentManagementMapper.batchUpdateActivate(ActivateStatusEnum.NOT_ACTIVATE.getCode(), null, null, null);
        }else {
            equipmentManagementMapper.batchUpdateActivate(ActivateStatusEnum.ACTIVATED.getCode(), new Date(), SecurityUtils.getUserId(), param.getIds());
        }
        equipmentManagementMapper.batchUpdateVehicleCompany(param.getIds(), param.getCompanyId());
        equipmentManagementMapper.batchUpdateDriverCompany(param.getIds(), param.getCompanyId());
        equipmentManagementMapper.batchUpdateEquipmentCompany(param.getIds(), param.getCompanyId());
    }

    /**
     * 设备批量导入
     * @param file
     * @param companyId
     */
    @Override
    public void importData(MultipartFile file, Long companyId) throws Exception {
        ExcelUtil<EquipmentManagement> util = new ExcelUtil<>(EquipmentManagement.class);
        List<EquipmentManagement> equipmentList = util.importExcel(file.getInputStream(), 1);
        if (ObjectUtils.isEmpty(equipmentList)) throw new ServiceException("数据解析失败，请检查文件！");
        //开始处理数据
        List<String> emptyError = new ArrayList<>();
        for (int i = 0; i < equipmentList.size(); i++) {
            EquipmentManagement equipment = equipmentList.get(i);
            //校验必填项，设备号和设备型号是必填项
            if (StringUtils.isEmpty(equipment.getDeviceId())){
                emptyError.add("第" + (i + 3) + "行数据,设备号不能为空！");
            }else if (equipment.getDeviceModel() == null){
                emptyError.add("第" + (i + 3) + "行数据,设备型号不能为空！");
            }
        }
        if (!emptyError.isEmpty()) throw new ServiceException("导入失败，数据存在错误：" + emptyError);
        //判断设备号是否已存在
        List<EquipmentManagement> exitDeviceList = equipmentManagementMapper.selectList(new QueryWrapper<EquipmentManagement>().in("device_id",
                equipmentList.stream().filter(e -> StringUtils.isNotEmpty(e.getDeviceId())).map(EquipmentManagement::getDeviceId).collect(Collectors.toList())));
        if (!ObjectUtils.isEmpty(exitDeviceList)) throw new ServiceException("导入失败，以下设备号已存在：" +
                exitDeviceList.stream().map(EquipmentManagement::getDeviceId).collect(Collectors.toList()));
        //判断sim卡是否存在
        List<String> simIds = equipmentList.stream().filter(e -> StringUtils.isNotEmpty(e.getSimId())).map(EquipmentManagement::getSimId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(simIds)) {
            List<EquipmentManagement> exitSimList = equipmentManagementMapper.selectList(new QueryWrapper<EquipmentManagement>().in("sim_id", simIds));
            if (!ObjectUtils.isEmpty(exitSimList)) throw new ServiceException("导入失败，以下sim卡已存在：" +
                    exitSimList.stream().map(EquipmentManagement::getSimId).collect(Collectors.toList()));
            List<EquipmentManagement> simErrorList = equipmentList.stream().filter(i -> StringUtils.isNotEmpty(i.getSimId()) && !ComLbsUtils.simIdCheck(i.getSimId())).collect(Collectors.toList());
            if (!ObjectUtils.isEmpty(simErrorList)) throw new ServiceException("导入失败，以下sim卡号不合法：" +
                    simErrorList.stream().map(EquipmentManagement::getSimId).collect(Collectors.toList()));
        }
        // 激活状态判定（如果是添加到出厂待销售的公司中，则设为未激活，否则设为激活）
        int activateStatus = deptService.getWaitSaleCompany().getDeptId().equals(companyId) ? 0 : 1;
        Long userId = SecurityUtils.getUserId();
        equipmentList.stream().forEach(i -> {
                i.setCompanyId(companyId)
                .setCheckStatus(0) //自检状态
                .setActivateStatus(activateStatus) //激活状态
                .setActivateTime(new Date())
                .setActivateUserId(userId);
        });
        saveOrUpdateBatch(equipmentList);
    }

    /**
     * 设备号重复校验
     * @param deviceId
     * @param id
     * @return
     */
    @Override
    public void checkExistDeviceId(String deviceId, Long id){
        EquipmentManagement equipment = equipmentManagementMapper.selectOne(new QueryWrapper<EquipmentManagement>().eq("device_id", deviceId));
        if (equipment == null) return;
        if (id == null || !id.equals(equipment.getId())) throw new ServiceException("设备号已存在");
    }

    /**
     * SIM卡重复校验
     * @param iccid
     * @param id
     * @return
     */
    @Override
    public void checkExistSimId(String iccid, Long id){
        EquipmentManagement equipment = equipmentManagementMapper.selectOne(new QueryWrapper<EquipmentManagement>().eq("sim_id", iccid));
        if (equipment == null) return;
        if (id == null || !id.equals(equipment.getId())) throw new ServiceException("SIM卡已被占用");
    }

    /**
     * 查询设备名称和公司名称
     */
    @Override
    public List<ComDvoName> selectDeviceAndCompanyName(List<String> deviceIds){
        return equipmentManagementMapper.listDeviceAndCompanyName(deviceIds);
    }

    /**
     * 查询设备名称和公司名称
     */
    @Override
    public ComDvoName selectDeviceAndCompanyName(String deviceId){
        return equipmentManagementMapper.getDeviceAndCompanyName(deviceId);
    }

    /**
     * 查询负责人信息
     * @param companyIds
     * @return
     */
    @Override
    public List<DeviceDriver> listDriver(List<Long> companyIds){
        return equipmentManagementMapper.listDriver(companyIds);
    }

    /**
     * 查询设备名称和设备号
     */
    @DataScope
    @Override
    public List<Map<String, Object>> listNumberPlateDeviceIdByName(JSONObject param){
        return equipmentManagementMapper.listNumberPlateDeviceIdByName(param);
    }

    /**
     * 查询监管类型列表
     * @return
     */
    @DataScope
    @Override
    public List<Integer> listObjType(JSONObject param){
        return equipmentManagementMapper.listObjType(param);
    }
}
